/**
 * @version 2.2
 * @author lineshow  2011/7-2011/12
 * @description  transform the jquery grid plugin to custom grid used by specific corporation
 * 
 */

/**
 * 
 * 列属性结构体
 * 
 * @param facadeName
 * @param name
 * @param index
 * @param width
 * @param align
 * @param sortable
 * @returns {ColumnAttr}
 */

function ColumnAttr(facadeName, name, index, width, align, sortable,
		editable,edittype,hiddenornot) {
	this.facadeName = facadeName;
	this.name = name;
	this.index = index;
	this.width = !!width ? width : 0;
	this.align = !!align ? align : "left";
	this.sortable = !!sortable ? sortable : false;
	this.editable = !!editable ? editable : false;
	this.edittype = !!edittype ? edittype : "text";
	this.formatter = undefined;
	this.formatoptions = undefined;
	this.hidden = !!hiddenornot ? hiddenornot : false;
};
/**
 * 设置列格式化类型
 */
ColumnAttr.prototype.setFormatter = function(formatter) {
	this.formatter = formatter;
}
/**
 * 设置列日期显示格式
 */
ColumnAttr.prototype.setDateFormat = function(format) {
	// this.formatoptions = new Object();
	this.formatoptions = {
		newformat : format
	};
}

/**
 * 
 * @param gridid
 *            grid挂载点
 * @param fbId
 *            底部工具栏挂载点
 * @param tbId
 *            顶部工具栏挂载点
 * @returns {FaceGrid}
 */

function FaceGrid(gridid, fbId, tbId) {
	this.beanGrid = this;
	this.gridId = gridid; // grid 挂载点
	this.footbarMnt = fbId; // 底部工具栏（包括分页）挂载点
	this.topBarMnt = tbId; // 上方工具栏挂载点
	this.queryBtId = null; // 查询按钮ID
	this.queryMntId = null; // 查询条件控件挂载点
	this.extraQueryIds = null; // 额外查询条件
	this.defaultQueryIds = null; //默认的查询条件
	this.url = null; // 访问地址
	this.datatype = "xml"; // 读取数据方式
	this.columnAttrList = new Array(); // 列属性
	this.levelColNames = []; // 多级表头设置
	this.autowidth = false; // 自动宽度
	this.rowNum = 10; // 默认页显示行
	this.page = this.page; // 默认显示第几页
//	this.rowList = [10, 20, 30, 50, 100 ]; // 可选择的页显示行数
	this.sortname = ""; // 默认排序列
	this.viewrecords = true; // 显示总行数
	this.sortorder = "desc"; // grid 数据排序方式
	this.caption = ""; // grid标题
	this.loadComplete = null; // grid载入数据完成 回调函数
	this.width = "700"; // grid 宽度
	this.height = "100%"; // grid高度 eg. 100% 表示grid 随内容高度变化
	this.checkable = false; // 是否显示checkbox
	this.showRowIndex = false; // 是否显示序号
	this.toppager = false; // 是否开启上方工具栏
	this.querySelIdCrowd = []; // 查询控件条件ID丛
	this.queryCustomIdCrowd = []; // 额外查询条件ID丛
	this.queryDefaultIdCrowd = []; // 额外查询条件ID丛
	this.cellurl = null; // 编辑保存路径
	this.excel_export = false; // 是否可导出excel
	this.isRemoteReq = 'xml'; // [local] 第一次进入页面不加载数据 [xml]加载数据
	this.seizeQuery = false; // 前后翻页时 是否考虑携带即时查询条件 默认不携带
	this.attendQuery = true; //第一次进入页面是否携带查询条件   默认携带
	this.onSelectRow = null; // checkbox 单选触发
	this.onSelectAll = null; //checkbox 全选触发
	this.multikey = false;	// 键盘辅助键  optional:['ctrlKey'|'shiftKey'|'altKey']
	this.multiboxonly = false; //仅点选checkbox 才能选中 
	this.headerAutoWrap = false; //表头自动换行
	this.loadOnce = false;
};

/**
 * 获取grid Dom
 * 
 * @param columnAttrList
 *            array
 * @returns gridObj
 */
FaceGrid.prototype.getGridDom = function() {
	return this.beanGrid;
};

/**
 * 设置列属性
 * 
 * @param columnAttrList
 *            array
 */
FaceGrid.prototype.setColumnAttrs = function(columnAttrList) {
	this.columnAttrList = columnAttrList;
};

/**
 * grid数据来源
 * 
 * @param url
 *            string
 */
FaceGrid.prototype.setUrl = function(url) {
	this.url = url;
};

/**
 * @deprecated
 */
FaceGrid.prototype.setDataType = function(datatype) {
	this.datatype = datatype;
};

/**
 * 默认每页显示行数
 * 
 * @param rownum
 *            numeral
 */
FaceGrid.prototype.setRowNum = function(rownum) {
	this.rowNum = rownum;
};

/**
 * 默认每页显示行数
 * 
 * @param rownum
 *            numeral
 */
FaceGrid.prototype.getRowNum = function() {
	return this.rowNum;
};

/**
 * 表头自动换行
 * 
 * @param rownum
 *            numeral
 */
FaceGrid.prototype.setHeaderAutoWrap = function(headerAutoWrap) {
	this.headerAutoWrap = headerAutoWrap; 
};

/**
 * 表头自动换行
 * 
 * @param rownum
 *            numeral
 */
FaceGrid.prototype.getHeaderAutoWrap = function() {
	return this.headerAutoWrap;
};

/**
 * 默认每页显示行数
 * 
 * @param rownum
 *            numeral
 */
FaceGrid.prototype.setPage = function(page) {
	this.page = page;
};

/**
 * 默认每页显示行数
 * 
 * @param rownum
 *            numeral
 */
FaceGrid.prototype.getPage = function() {
	return this.page;
};

/**
 * @deprecated
 */
FaceGrid.prototype.setRowList = function(rowlist) {
	this.rowList = rowlist;
};

/**
 * 默认排序列
 * 
 * @param sortname
 *            string column name
 */
FaceGrid.prototype.setDefaultSortName = function(sortname) {
	this.sortname = sortname;
};

/**
 * grid 排序方式
 * 
 * @param sortorder
 *            string[desc asc]
 */
FaceGrid.prototype.setDefaultSortorder = function(sortorder) {
	this.sortorder = sortorder;
};

/**
 * 设置标题
 * 
 * @deprecated
 */
FaceGrid.prototype.setCaption = function(caption) {
	this.caption = caption;
};

/**
 * 显示总条数
 * 
 * @param viewrecords
 *            boolean
 */
FaceGrid.prototype.showRecords = function(viewrecords) {
	this.viewrecords = viewrecords;
};

/**
 * grid 宽度
 * 
 * @param numeral
 */
FaceGrid.prototype.setWidth = function(width) {
	this.width = width;
};

/**
 * grid 高度
 * 
 * @param numeral
 */
FaceGrid.prototype.setHeight = function(height) {
	this.height = height;
};

/**
 * 设置grid加载完成之后的动作
 * 
 * @param func
 *            call back function
 */
FaceGrid.prototype.setLoadComplete = function(func) {
	this.loadComplete = func;
};

/**
 * levelColNames 多级表头 『格式：[{'列名':'起始列序号,步长','列名':'起始列序号,步长'},...]』
 */
FaceGrid.prototype.setLevelColNames = function(levelColNames) { // str
	this.levelColNames = levelColNames;
};

/**
 * @param boolean
 *            是否显示行checkbox
 */
FaceGrid.prototype.setCheckAble = function(checkable) {
	this.checkable = checkable;
};

/**
 * @checkway boolean true:单选  false:多选 
 */
FaceGrid.prototype.setCheckSingleRow = function(checkway) { // boolean
	this.multiboxonly = checkway;
};

/**
 * @param showRowIndex
 *            boolean 是否显示行序号
 */
FaceGrid.prototype.setShowRowIndex = function(showRowIndex) {
	this.showRowIndex = showRowIndex;
};

FaceGrid.prototype.setRowheaderLen = function(rowheaderLen) {
	this.rowheaderLen = rowheaderLen;
};
/**
 * loadonce boolean
 */
FaceGrid.prototype.setLoadOnce = function(loadonce){
	this.loadonce = loadonce;
	if(this.loadonce){
		this.rowNum = 100000;
	}
};

/**
 * 在此设置查询控件挂载点
 * 
 * @param queryBtId
 *            string 查询按钮ID
 * @param queryMnt：string
 *            查询box外围divID
 * @param extraQueryIds
 *            array 额外控件ID如 text radio等
 */
FaceGrid.prototype.setQueryBox = function(queryBtId, queryMnt, extraQueryIds,defaultIds) {
	this.queryBtId = queryBtId;
	this.queryMntId = queryMnt;
	this.extraQueryIds = extraQueryIds;
	this.defaultQueryIds = defaultIds;
};

/**
 * 是否显示顶部工具栏
 * 
 * @param toppager
 *            boolean
 */
FaceGrid.prototype.setToppager = function(toppager) { // boolean
	this.toppager = toppager;
};

/**
 * 查询前置方法-查询参数收集
 */
FaceGrid.prototype.preDealOnQuery = function() {
	var queryKVStr = '';
	if(this.queryDefaultIdCrowd && this.queryDefaultIdCrowd.length > 0){
		for(var i = 0;i < this.queryDefaultIdCrowd.length; i++){
			var queryId = this.queryDefaultIdCrowd[i];
			var queryObj = $("#" + queryId);
			var queryCellValue = $.trim(queryObj.val());
			if (!!queryCellValue)
				queryKVStr += '[tear]' + queryId + ':' + queryCellValue;
		}
	}
	var sdata = {};
	if (!this.seizeQuery&&!this.attendQuery) {
		return sdata['searchString'] = queryKVStr == '' ? '' : queryKVStr.substring(6);;
	}
	this.attendQuery = false;
	
	var queryMnt = $("#"+this.queryMntId);
	for ( var i = 0; i < this.querySelIdCrowd.length; i++) {
		var queryId = this.querySelIdCrowd[i];
		var destContral = queryMnt.find('#' + queryId);
		if(destContral.size()==0){
			continue;
		}
	//	var destContral = $("#"+this.queryMntId).find('#' + queryId, $('#' + selId).parent().next());
		var queryValue = destContral.val();
		var queryCellValue = $.trim(queryValue);
		if (!!queryCellValue) {
			var ttitle = destContral.attr("title");
			if (destContral.is("select")) {
				var queryText = destContral.find("option:selected").text();
				queryKVStr += '[tear]' + queryId + ':' + queryValue;
				queryKVStr += '[tear]' + queryId + '_name' + ':' + queryText;
			} else {
				if(ttitle == queryCellValue){
					continue;
				}
				queryKVStr += '[tear]' + queryId + ':' + queryCellValue;
			}
		}
	}

	for ( var i = 0; i < this.queryCustomIdCrowd.length; i++) {
		var queryId = this.queryCustomIdCrowd[i];
		var queryObj = $("#" + queryId);
		if (queryObj.is("input")
				&& ((queryObj.attr("type") == "radio" || queryObj.attr("type") == "checkbox") && !queryObj
						.attr("checked"))) {
			continue;
		}
		var queryCellValue = $.trim(queryObj.val());
		if (!!queryCellValue)
			queryKVStr += '[tear]' + queryId + ':' + queryCellValue;
	}
	sdata['searchString'] = queryKVStr == '' ? '' : queryKVStr.substring(6);
	return sdata;
};

/**
 * 设置能否导出excel
 * 
 * @param can
 *            boolean
 */
FaceGrid.prototype.setCanExportExcel = function(can) {
	this.excel_export = can;
};

/**
 * 设置单元格编辑后负责数据保存的url
 * 
 * @param cellurl
 *            string
 */
FaceGrid.prototype.setCellUrl = function(cellurl) {
	this.cellurl = cellurl;
};
/**
 * 设置进入第一次页面时 是否默认加载数据
 * 
 * @param load
 *            boolean [default:false]
 */
FaceGrid.prototype.setLazyLoad = function(load) {
	if (load) {
		this.isRemoteReq = 'local';
	} else {
		this.isRemoteReq = 'xml';
	}
};

/**
 * building grid
 */
FaceGrid.prototype.build = function() {
	var colNameStr = [];
	var newColModel = [];
	for ( var i = 0; i < this.columnAttrList.length; i++) { // 分配列属性
		var ca = this.columnAttrList[i];
		colNameStr.push(ca.facadeName);
		var columnAttr = {
			name : ca.name,
			index : ca.index,
			width : ca.width,
			align : ca.align,
			sortable : false,
			sorttype : "float",
			formatter : ca.formatter,
			formatoptions : ca.formatoptions,
			editable : ca.editable,
			cellattr : colspan = 2,
			edittype : ca.edittype,
			hidden : ca.hidden,
			resizable : false
		};
		newColModel.push(columnAttr);
	}
	if (!!this.topBarMnt) { // 是否加载顶部工具栏
		this.toppager = true;
	}
	if(!!this.defaultQueryIds){
		this.queryDefaultIdCrowd = this.defaultQueryIds;
	}
	if (!!this.queryBtId) {
		var queryTableObj = $("#"+this.queryMntId);
		var querySels = [];
		$("select,input", queryTableObj).each(
				function() {
					querySels.push($(this).attr('id'));
				});
		var customQuerys = [];
		if (!!this.extraQueryIds) {
			customQuerys = this.extraQueryIds;
		}
		var $bt = this;
		this.querySelIdCrowd = querySels;
		this.queryCustomIdCrowd = customQuerys;
		$('#' + this.queryBtId).click(function() {
			$bt.seizeQuery = true;
			jQuery('#' + $bt.gridId).jqGrid('queryTrigger');
			$bt.seizeQuery = false;
		});
	}
	var excelVisible = false;
	if (this.excel_export) {
		excelVisible = true;
	}
	var cxhGrid = this;
	this.beanGrid = jQuery('#' + this.gridId).jqGrid({
		url : this.url,
		datatype : this.datatype,
		mtype : "post",
		coverColNames : this.levelColNames,
		colNames : colNameStr,
		colModel : newColModel,
		rowNum : this.rowNum,
		page : this.page,
		rowList : this.rowList,
		pager : this.footbarMnt,
		sortname : this.sortname,
		viewrecords : this.viewrecords,
		sortorder : this.sortorder,
		autowidth : this.autowidth,
		caption : this.caption,
		width : this.width,
		height : this.height,
		beforeProcessing : null, //载入数据前
		loadComplete : this.loadComplete,//载入数据后
		multiselect : this.checkable,
		rownumbers : this.showRowIndex,
		rownumWidth : 20, // 序号列宽度
		rowheaderLen : this.rowheaderLen,
		headerAutoWrap:this.headerAutoWrap,
		toppager : this.toppager,
		toppagerMnt : this.topBarMnt,
		gridview : false,
		hidegrid : true, // grid is foldable or not
		forceFit : true,
		shrinkToFit : true,
		cellEdit : false, // 单元格可编辑
		clickEditAble : true, // 不允许单击单元格进行编辑
		cellurl : this.cellurl,
		queryIdCrowd : this.queryIdCrowd,
		multiboxonly : this.multiboxonly,
		multikey : this.multikey, 
		serializeGridData : function(queryData) {
			var sdata = cxhGrid.preDealOnQuery();
			$.extend(queryData, sdata);
			return queryData;
		},
		onSelectRow : this.onSelectRow,
		onSelectAll : this.onSelectAll,
		excel_export : this.excel_export,
		datatype : this.isRemoteReq, // 本地加载 or 远程加载 ['local' or 'xml']
		loadonce:this.loadonce,
	// direction : "rtl", //grid整体反向 用
		loadError : function(xhr,st,err) {
			//"类型："+st+"，返回："+xhr.status + " "+xhr.statusText
		//	scmError("登录超时，请重新登录",'450px',0); 
		}
	});
	// this.beanGrid.jqGrid('bindKeys', {"onEnter":function( rowid ) {
	// alert("You enter a row with id:"+rowid)} } ); // 与按键关联
};
